package com.atguigu.sparearray;


/*
* 将矩阵转换为稀疏矩阵，在转换为矩阵
* */
public class SpareArray {
    public static void main(String[] args) {
        //1.创建数组
        int[][] chessArr=new int[11][11];
        chessArr[1][2]=1;
        chessArr[2][3]=2;
        chessArr[4][3]=4;
        System.out.println("查看创建得数组");

        for (int[] row:chessArr) {
            for (int data:row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();

        }
        //2.创建稀疏数组
        //2.1获得稀疏数数组得长和宽
        int len=chessArr[0].length;
        int kuan=chessArr.length;
        //2.2得到非0元素的个数
        int sum=0;
        for (int[] row:chessArr) {
            for (int data : row) {
                if (data != 0) {
                    sum++;
                }
            }
        }
        //2.3创建稀疏数组
        int[][] spare=new int[sum+1][3];
        //2.4添加第一行元素
        spare[0][0]=len;
        spare[0][1]=kuan;
        spare[0][2]=sum;
        //2.5添加非零元素
        int count=0;
        for (int i = 0; i < chessArr.length; i++) {
            for (int j = 0; j < chessArr[i].length; j++) {
                if(chessArr[i][j]!=0){
                    count++;
                   spare[count][0]=i;
                   spare[count][1]=j;
                   spare[count][2]=chessArr[i][j];
                }
            }
            System.out.println();
        }
        //3.查看创建的稀疏数组
        System.out.println("查看创建的稀疏矩阵");
        for(int[] row:spare){
            for (int data:row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        //4.将稀疏矩阵转换成数组
        int[][] chessArr2=new int[spare[0][0]][spare[0][1]];
        for (int i = 1; i < spare.length; i++) {
           chessArr2[spare[i][0]][spare[i][1]]=spare[i][2];
        }
        //5.查看转换后的矩阵
        System.out.println("查看稀疏矩阵转换后的矩阵");
        for (int[] row:chessArr2) {
            for (int data:row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

    }
}
